package com.jhd.fuzhou.util;

import android.content.Context;
import android.graphics.Bitmap;

import com.alibaba.fastjson.JSON;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.github.barteksc.pdfviewer.util.FitPolicy;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.SuperviseEnclosureVo;
import com.jhd.fuzhou.vo.SupervisionInspectionVo;
import com.jhd.fuzhou.vo.Upload;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

public class UploadFile {
    public static void uploadFile(FuzhouApplication application, Context context, SupervisionInspectionVo supervisionInspectionVo,File file, String name, String type,String taskType){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.UC());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, Object> params = new HashMap<>();
        params.put("type", "rcjd");
        params.put("isPublic",true);
        RequestBody fileRQ = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part part=MultipartBody.Part.createFormData("file", file.getName(), fileRQ);
        Call<JsonForResult> jsonForResultCall = vs.uploadFileByPos(application.getAccessToken(),params,part);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try{
                    if(response.code()==200){
                        JsonForResult jsonForResult = (JsonForResult) response.body();
                        if (jsonForResult != null && jsonForResult.isSuccess()) {
                            if (jsonForResult.getData() != null) {
                                //先删除
                                List<SuperviseEnclosureVo> superviseEnclosureVoList;
                                if(taskType.equals("专项监督")){
                                    superviseEnclosureVoList= supervisionInspectionVo.getDocumentAttachmentList();
                                }else{
                                    superviseEnclosureVoList= supervisionInspectionVo.getSuperviseEnclosureVoList();
                                }
                                if(superviseEnclosureVoList!=null){
                                    for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
                                        if(superviseEnclosureVo.getEnclosureName().equals(name)){
                                            superviseEnclosureVoList.remove(superviseEnclosureVo);
                                            break;
                                        }
                                    }
                                }else{
                                    superviseEnclosureVoList=new ArrayList<>();
                                }
                                //再加入
                                Upload upload = JSON.parseObject(jsonForResult.getData().toString(), Upload.class);
                                SuperviseEnclosureVo superviseEnclosureVo=new SuperviseEnclosureVo();
                                superviseEnclosureVo.setEnclosureName(name);
                                superviseEnclosureVo.setEnclosureUrl(upload.getUrl());
                                superviseEnclosureVo.setType(type);
                                superviseEnclosureVo.setDocumentNo("");
                                superviseEnclosureVoList.add(superviseEnclosureVo);
                                if(taskType.equals("专项监督")){
                                    supervisionInspectionVo.setDocumentAttachmentList(superviseEnclosureVoList);
                                }else{
                                    supervisionInspectionVo.setSuperviseEnclosureVoList(superviseEnclosureVoList);
                                }
                            }
                        }

                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "上传文件失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    public static void saveDocNo(SupervisionInspectionVo supervisionInspectionVo,String documentNo,String name){
        SuperviseEnclosureVo superviseEnclosureVo=supervisionInspectionVo.getDocumentNo();
        if(superviseEnclosureVo==null) {
            superviseEnclosureVo=new SuperviseEnclosureVo();
            superviseEnclosureVo.setEnclosureName(name);
            superviseEnclosureVo.setDocumentNo(documentNo);
            supervisionInspectionVo.setDocumentNo(superviseEnclosureVo);
        }
    }

    /*public static void saveDocNo(SupervisionInspectionVo supervisionInspectionVo,String documentNo,String name){
        List<SuperviseEnclosureVo> superviseEnclosureVoList=supervisionInspectionVo.getCheckDocumentNo();
        if(superviseEnclosureVoList!=null){
            for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
                if(superviseEnclosureVo.getEnclosureName().equals(name)){
                    superviseEnclosureVoList.remove(superviseEnclosureVo);
                    break;
                }
            }
        }else{
            superviseEnclosureVoList=new ArrayList<>();
        }
        //再加入
        SuperviseEnclosureVo superviseEnclosureVo=new SuperviseEnclosureVo();
        superviseEnclosureVo.setEnclosureName(name);
        superviseEnclosureVo.setDocumentNo(documentNo);
        superviseEnclosureVoList.add(superviseEnclosureVo);
        supervisionInspectionVo.setCheckDocumentNo(superviseEnclosureVoList);
    }*/


    public static void uploadFileAndDocNo(FuzhouApplication application, Context context, SupervisionInspectionVo supervisionInspectionVo,String documentNo,File file, String name, String type,String taskType){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.UC());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, Object> params = new HashMap<>();
        params.put("type", "rcjd");
        params.put("isPublic",true);
        RequestBody fileRQ = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part part=MultipartBody.Part.createFormData("file", file.getName(), fileRQ);
        Call<JsonForResult> jsonForResultCall = vs.uploadFileByPos(application.getAccessToken(),params,part);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try{
                    if(response.code()==200){
                        JsonForResult jsonForResult = (JsonForResult) response.body();
                        if (jsonForResult != null && jsonForResult.isSuccess()) {
                            if (jsonForResult.getData() != null) {
                                //先删除
                                List<SuperviseEnclosureVo> superviseEnclosureVoList=null;
                                if(taskType.equals("专项监督")){
                                    superviseEnclosureVoList= supervisionInspectionVo.getDocumentAttachmentList();
                                }else{
                                    superviseEnclosureVoList= supervisionInspectionVo.getSuperviseEnclosureVoList();
                                }
                                if(superviseEnclosureVoList!=null){
                                    for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
                                        if(superviseEnclosureVo.getEnclosureName().equals(name)){
                                            superviseEnclosureVoList.remove(superviseEnclosureVo);
                                            break;
                                        }
                                    }
                                }else{
                                    superviseEnclosureVoList=new ArrayList<>();
                                }
                                //再加入
                                Upload upload = JSON.parseObject(jsonForResult.getData().toString(), Upload.class);
                                SuperviseEnclosureVo superviseEnclosureVo=new SuperviseEnclosureVo();
                                superviseEnclosureVo.setEnclosureName(name);
                                superviseEnclosureVo.setEnclosureUrl(upload.getUrl());
                                superviseEnclosureVo.setType(type);
                                superviseEnclosureVo.setDocumentNo(documentNo);
                                superviseEnclosureVoList.add(superviseEnclosureVo);
                                if(taskType.equals("专项监督")){
                                    supervisionInspectionVo.setDocumentAttachmentList(superviseEnclosureVoList);
                                }else{
                                    supervisionInspectionVo.setSuperviseEnclosureVoList(superviseEnclosureVoList);
                                }
                            }

                        }

                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "上传文件失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public static void saveDocumentNoRecord( FuzhouApplication application,Context context, SupervisionInspectionVo supervisionInspectionVo,String taskType){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
//        Retrofit retrofit = UtilHelper.retrofit(application,"http://tech.lhtsky.top:42312/");//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        List<Map<String, Object>> params = new ArrayList<>();
        List<SuperviseEnclosureVo> superviseEnclosureVoList=null ;
        if(taskType.equals("专项监督")){
            superviseEnclosureVoList=supervisionInspectionVo.getDocumentAttachmentList();
        }else{
            superviseEnclosureVoList=supervisionInspectionVo.getSuperviseEnclosureVoList();
        }
        for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
            if("监督意见书".equals(superviseEnclosureVo.getEnclosureName())||"现场笔录".equals(superviseEnclosureVo.getEnclosureName())){
                Map<String, Object> param=new HashMap<>();
                param.put("documentUrl",superviseEnclosureVo.getEnclosureUrl());//编号
                param.put("documentNo",superviseEnclosureVo.getDocumentNo());
                params.add(param);
            }
        }
        if(params.size()!=0){
            RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"),
                    JSON.toJSONString(params));
            Call<JsonForResult> jsonForResultCall = vs.saveDocumentNoRecord(application.getAccessToken(),requestBody);
            jsonForResultCall.enqueue(new Callback<JsonForResult>() {
                @Override
                public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                    try{
                        if(response.code()==200){
                            JsonForResult jsonForResult = (JsonForResult) response.body();
                            if (jsonForResult != null && jsonForResult.isSuccess()) {

                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<JsonForResult> call, Throwable t) {
                    String msg = "文书号保存失败!";
                    UtilHelper.alertMsg(context, "错误", msg);
                }
            });
        }
    }


    public static void showPDF(PDFView pdfView, File file, Context context){
        try {
            pdfView.fromStream(new FileInputStream(file))
                    .enableSwipe(true)
                    .swipeHorizontal(false)
                    .enableDoubletap(true)
                    .defaultPage(0)
                    .enableAnnotationRendering(false)
                    .password(null)
                    .scrollHandle(new DefaultScrollHandle(context))
                    .enableAntialiasing(true)
                    .spacing(0)
                    .autoSpacing(false)
                    .pageFitPolicy(FitPolicy.WIDTH)
                    .fitEachPage(false)
                    .pageSnap(false)
                    .pageFling(false)
                    .nightMode(false)
                    .load();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void saveBitmapFile(Context context,Bitmap bitmap,String name){
        File file=new File(context.getExternalFilesDir(null).getPath()+"/"+ name);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copyFile(String oldPath, String newPath,String name,Context context){
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                File destDir = new File(newPath);
                if (!destDir.exists()) {
                    destDir.mkdirs();
                }
                FileOutputStream fs = new FileOutputStream(newPath+name);
                byte[] buffer = new byte[1024];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
            CustomToast.showText(context,"文件保存成功,路径为:"+newPath,3000,0,0).show();
        }
        catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
        }
    }

    public static void copyPhoto(Bitmap bitmap, String newPath,String name,Context context){
        try {
            File file=new File(newPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            FileOutputStream fs = new FileOutputStream(new File(newPath+name));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fs);
            fs.flush();
            fs.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 复制整个文件夹内容
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a=new File(oldPath);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                if(oldPath.endsWith(File.separator)){
                    temp=new File(oldPath+file[i]);
                }
                else{
                    temp=new File(oldPath+File.separator+file[i]);
                }

                if(temp.isFile()){
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if(temp.isDirectory()){//如果是子文件夹
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
        }
        catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }


}
